// StringResourceExtension.cs
//
// Copyright (c) Sunday, July 27, 2008 Mike Strobel
//
// This source code is subject to the terms of the Microsoft Reciprocal License (Ms-RL).
// For details, see <http://www.opensource.org/licenses/ms-rl.html>.
//
// All other rights reserved.

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

using Supremacy.Annotations;

namespace SupremacyEditor
{
    [MarkupExtensionReturnType(typeof(object))]
    public class StringResourceExtension : MarkupExtension
    {
        #region Fields
        private readonly string _key;
        private StringResourceProvider _provider;
        #endregion

        #region Constructors
        public StringResourceExtension() : this(String.Empty) {}

        public StringResourceExtension(string key)
        {
            _key = key;
        }
        #endregion

        #region Properties
        [CanBeNull]
        [DefaultValue(null)]
        public StringResourceProvider Provider
        {
            get { return _provider; }
            set { _provider = value; }
        }
        #endregion

        #region Methods
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            Binding binding;

            if (String.IsNullOrEmpty(_key))
                return String.Empty;

            if (_provider != null)
            {
                binding = new Binding
                {
                    Source = this,
                    Path = new PropertyPath("Provider[" + _key + "]"),
                    Mode = BindingMode.OneTime
                };
            }
            else
            {
                binding = StringResourceProvider.CreateTextBinding(_key);
            }

            return binding.ProvideValue(serviceProvider);
        }
        #endregion
    }
}